<template>
  <div class="app-container">
    <div style="margin-bottom: 20px;" class="clearfix">
      <el-input
        v-model="listQuery.keyword"
        placeholder="请输入工号/姓名/手机号"
        style="width: 200px;"
        class="filter-item"
        clearable
        @keyup.enter.native="goToSearch"
        @input="defaultList"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        style="margin-left: 20px;"
        @click="goToSearch"
      >搜索</el-button>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-plus"
        style="float:right"
        @click="handleAdd"
      >新增</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :element-loading-text="g.loadingStr"
      :header-cell-style="{background:g.mainColor}"
    >
      <el-table-column label="序号" align="center" width="100" fixed>
        <template slot-scope="{row}">
          <span>{{ row.workNo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="部门" align="center">
        <template slot-scope="{row}">
          <span>{{ row.departmentName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="职位" align="center">
        <template slot-scope="{row}">
          <span>{{ row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center">
        <template slot-scope="{row}">
          <span>{{ row.realName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系手机号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="{row}">
          <span>{{ row.adminStatus === 1 ? '启用' : '禁用' }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="320px">
        <template slot-scope="{row,$index}">
          <el-button
            v-if="row.adminStatus === 1"
            type="primary"
            size="mini"
            @click="handleStatus(row,$index)"
          >禁用</el-button>
          <el-button v-else type="primary" size="mini" @click="handleStatus(row,$index)">启用</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
          <el-button type="primary" size="mini" @click="handleDetail(row)">详情</el-button>
          <el-button type="danger" size="mini" @click="handleDel(row,$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.currentPage"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="dialogType"
      :visible.sync="dialogVisible"
      width="800px"
      @close="$refs['form'].clearValidate()"
      @opened="$refs['form'].clearValidate()"
    >
      <el-form ref="form" :model="form" label-width="120px" :rules="formRules">
        <label
          style="width: 120px;height: 50px;line-height: 50px;font-size:18px;text-align:right;display:block;"
        >基本信息</label>
        <el-form-item label="头像">
          <el-upload
            action="#"
            list-type="picture-card"
            :on-remove="handleRemove"
            :on-change="handleChange"
            :auto-upload="false"
            :class="{hide:hideUpload}"
            :file-list="imgsList"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="毕业院校" prop="graduationSchool">
          <el-input v-model="form.graduationSchool" placeholder="请输入毕业院校" clearable />
        </el-form-item>
        <el-form-item label="学历" prop="education">
          <el-select
            v-model="form.education"
            placeholder="请选择类型"
            clearable
            class="filter-item"
            style="width: 140px"
          >
            <el-option
              v-for="item in g.educationList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作经历">
          <el-input
            v-model="form.jobs"
            style="width:400px;"
            type="textarea"
            autosize
            placeholder="请输入工作经历"
            clearable
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="教育经历">
          <el-input
            v-model="form.experiences"
            style="width:400px;"
            type="textarea"
            autosize
            placeholder="请输入教育经历"
            clearable
            maxlength="200"
            show-word-limit
          />
          <el-tooltip class="item" effect="dark" placement="top">
            <div slot="content">
              <span>1.2004年至今在XXX公立学校任教16年</span>
              <br>
              <span>2.2003年哈佛硕士</span>
              <br>
              <span>3.2001年北京本科</span>
            </div>
            <el-button type="text" style="color:black; margin-left:10px;">帮助</el-button>
          </el-tooltip>
        </el-form-item>

        <label
          style="width: 120px;height: 50px;line-height: 50px;font-size:18px;text-align:right;display:block;"
        >职能信息</label>
        <el-form-item label="所属部门" prop="departmentId">
          <el-select
            v-model="form.departmentId"
            placeholder="请选择类型"
            clearable
            class="filter-item"
            style="width: 140px"
          >
            <el-option
              v-for="item in departmentAllList"
              :key="item.id"
              :label="item.departName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="职位" prop="roleId">
          <el-select
            v-model="form.roleId"
            placeholder="请选择类型"
            clearable
            class="filter-item"
            style="width: 140px"
            @change="handlePosition"
          >
            <el-option
              v-for="item in positionAllList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="身份" prop="identity">
          <el-select
            v-model="form.identity"
            placeholder="请选择类型"
            clearable
            class="filter-item"
            style="width: 140px"
          >
            <el-option
              v-for="item in g.userRoleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工号" prop="workNo">
          <el-input
            v-model.number="form.workNo"
            placeholder="请输入工号"
            clearable
            @change="validRepeatWorkNum"
          />
          <i v-if="isRegister == -1 " class="el-icon-check">通过</i>
          <i v-if="isRegister !== -1 && isRegister !== null" class="el-icon-close">工号已存在</i>
        </el-form-item>

        <label
          style="width: 120px;height: 50px;line-height: 50px;font-size:18px;text-align:right;display:block;"
        >账号信息</label>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="form.phone"
            placeholder="请输入员工的手机号"
            clearable
            :disabled="isPhone"
            @blur="validReoeatPhoneNum"
          />
          <i v-if="isPhoneNum == 0 && isPhoneNum !== null" class="el-icon-check">通过</i>
          <i v-if="isPhoneNum == 1 && isPhoneNum !== null" class="el-icon-close">电话已存在</i>
        </el-form-item>
        <el-form-item label="初始密码">
          <el-input v-model="form.password" placeholder="JBL123456" :disabled="isPassword" />
        </el-form-item>
        <el-form-item v-if="!isShowDetail">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import * as Employee from '@/api/system'
import md5 from 'js-md5'
export default {
  name: 'EmployeeList',
  directives: { waves },
  components: { Pagination },
  data() {
    var validatePhone = (rule, value, callback) => {
      if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    return {
      formRules: {
        realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        education: [
          { required: true, message: '请选择学历', trigger: 'change' }
        ],
        graduationSchool: [
          { required: true, message: '请输入毕业院校', trigger: 'blur' }
        ],
        jobs: [{ required: true, message: '请输入工作经历', trigger: 'blur' }],
        experiences: [
          { required: true, message: '请输入教育经历', trigger: 'blur' }
        ],
        departmentId: [
          { required: true, message: '请选择所属部门', trigger: 'change' }
        ],
        roleId: [{ required: true, message: '请选择职位', trigger: 'change' }],
        identity: [
          { required: true, message: '请选择身份', trigger: 'change' }
        ],
        phone: [{ validator: validatePhone, trigger: 'blur' }],
        workNo: [
          { required: true, message: '工号不能为空', trigger: 'blur' },
          { type: 'number', message: '工号必须为数字', trigger: 'blur' }
        ]
      },
      tableKey: 0,
      list: null,
      validateRepeatArray: null,
      total: 0,
      listLoading: true,
      listQuery: {
        currentPage: 1,
        pageSize: 10,
        orgId: 0,
        keyword: '',
        departmentId: ''
      },

      departmentAllList: [],
      positionAllList: [],
      editId: '',
      userId: '',
      form: {
        avatar: null,
        realName: '',
        sex: '1',
        graduationSchool: '',
        education: '1',
        jobs: '',
        experiences: '',
        departmentId: '',
        roleId: '',
        identity: '',
        workNo: '',
        phone: '',
        // password: md5('JBL123456')
        password: 'JBL123456'
      },
      dialogVisible: false,
      dialogType: '',
      roleName: '',
      imgsList: [],
      hideUpload: false,
      imgFile: null,
      isShowDetail: false,
      isPhoneNum: null,
      isRegister: null,
      isPassword: false,
      isPhone: false
    }
  },
  created() {},
  mounted() {
    this.getList()
  },
  methods: {
    validRepeatWorkNum() {
      this.getValidRepeatArray().then((res) => {
        this.isRegister = null
        if (this.form.workNo === '') return
        const repeatValidateArray = []
        for (const value of res) {
          repeatValidateArray.push(value['workNo'])
        }
        this.isRegister = repeatValidateArray.indexOf(this.form.workNo)
      })
    },
    validReoeatPhoneNum() {
      Employee.validatePhoneNumber({ phone: this.form.phone }).then((res) => {
        console.log(res.data.exist)
        this.isPhoneNum = res.data.exist === 1 ? 1 : 0
      })
    },
    getValidRepeatArray() {
      return new Promise((resolve, reject) => {
        Employee.organizeEmployeeList({
          currentPage: 1,
          pageSize: 2000,
          orgId: 0
        }).then((response) => {
          this.validateRepeatArray = response.data.data
          resolve(response.data.data)
        })
      })
    },
    resetForm() {
      this.imgsList = []
      this.hideUpload = false
      this.imgFile = null
      for (const item of Object.keys(this.form)) {
        this.form[item] = ''
      }
    },
    getList() {
      this.listLoading = true
      Employee.organizeEmployeeList(this.listQuery).then((response) => {
        this.list = response.data.data
        this.total =
          response.data.data.length === 0
            ? 1
            : (this.total = response.data.data.length)
        this.listLoading = false
      })
    },
    handleDetail(row) {
      this.resetForm()
      this.dialogType = '员工详情'
      this.dialogVisible = true
      this.isShowDetail = true
      if (this.departmentAllList.length === 0) {
        this.getDepartmentAllList()
      }
      if (this.positionAllList.length === 0) {
        this.getPositionAllList()
      }

      this.getEmployeeDetail(row['userId'])
    },
    handleUpdate(row) {
      console.log(row)
      this.resetForm()
      this.dialogType = '员工编辑'
      this.isRegister = null
      this.isPhoneNum = null
      this.isPhone = true
      this.dialogVisible = true
      this.isShowDetail = false
      this.isPassword = true
      if (this.departmentAllList.length === 0) {
        this.getDepartmentAllList()
      }
      if (this.positionAllList.length === 0) {
        this.getPositionAllList()
      }
      this.getEmployeeDetail(row['userId'])
    },
    getEmployeeDetail(employeeId) {
      Employee.getEmployeeDetail({
        userId: employeeId,
        orgId: 0
      }).then((response) => {
        console.log(response)
        const data = response.data
        if (data.avatar !== null && data.avatar !== '') {
          this.imgsList = [{ url: data.avatar }]
          this.hideUpload = true
        }
        this.form.avatar = data.avatar
        this.form.realName = data.realName
        this.form.sex = data.sex.toString()
        this.form.graduationSchool = data.graduationSchool
        this.form.education = data.education.toString()
        this.form.jobs = data.jobs
        this.form.experiences = data.experiences
        this.form.departmentId = data.departmentId.toString()
        this.form.roleId = data.roleId.toString()
        this.form.identity = data.identity.toString()
        this.form.workNo = data.workNo
        this.form.phone = data.phone
        this.roleName = data.roleName
        this.editId = data.id
        this.userId = data.userId
      })
    },
    handleAdd() {
      this.resetForm()
      this.dialogType = '员工新增'
      this.isRegister = null
      this.isPhoneNum = null
      this.isPhone = false
      this.dialogVisible = true
      this.isShowDetail = false
      this.isPassword = false
      if (this.departmentAllList.length === 0) {
        this.getDepartmentAllList()
      }
      if (this.positionAllList.length === 0) {
        this.getPositionAllList()
      }
    },
    getDepartmentAllList() {
      Employee.organizeDepartmentAllList({
        orgId: 0
      }).then((response) => {
        console.log(response)
        this.departmentAllList = response.data
      })
    },
    getPositionAllList() {
      Employee.organizePositionAllList({
        orgId: 0
      }).then((response) => {
        console.log(response)
        this.positionAllList = response.data
      })
    },
    // 选择职位
    handlePosition(e) {
      this.positionAllList.forEach(item => {
        if (item.id === e) {
          this.roleName = item.roleName
        }
      })
      console.log(this.roleName)
    },

    submit() {
      if (this.form.password === '') {
        this.form.password = 'JBL123456'
      }
      if (this.imgFile === null && this.form.avatar === null) {
        this.$message({ message: '请选择图片', type: 'error' })
        return
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.dialogType === '员工编辑') {
            if (this.imgFile !== null) {
              this.uploadImgToOss(this.imgFile).then((response) => {
                console.log('图片上传结果：' + JSON.stringify(response))
                this.form.avatar = response
                this.goToEdit()
              })
            } else {
              this.goToEdit()
            }
          } else {
            if (this.isPhoneNum !== 0 || this.isRegister !== -1) return
            if (this.imgFile !== null) {
              this.uploadImgToOss(this.imgFile).then((response) => {
                console.log('图片上传结果：' + JSON.stringify(response))
                this.form.avatar = response
                console.log(response)
                this.goToAdd()
              })
            } else {
              this.goToAdd()
            }
          }
        }
      })
    },
    goToAdd() {
      Employee.organizeEmployeeAdd({
        realName: this.form.realName,
        password: md5(this.form.password),
        phone: this.form.phone,
        orgId: 0,
        identity: this.form.identity,
        departmentId: this.form.departmentId,
        roleId: this.form.roleId,
        workNo: this.form.workNo,
        avatar: this.form.avatar,
        sex: this.form.sex,
        graduationSchool: this.form.graduationSchool,
        education: this.form.education,
        jobs: this.form.jobs,
        experiences: this.form.experiences
      }).then((response) => {
        console.log(response)
        this.$message({ message: '提交成功', type: 'success' })
        this.dialogVisible = false
        this.getList()
        this.imgFile = null
        this.form.avatar = null
        this.isPhone = false
      })
    },
    goToEdit() {
      Employee.organizeEmployeeEdit({
        avatar: this.form.avatar,
        realName: this.form.realName,
        sex: this.form.sex,
        graduationSchool: this.form.graduationSchool,
        education: this.form.education,
        workNo: this.form.workNo,
        departmentId: this.form.departmentId,
        roleId: this.form.roleId,
        roleName: this.roleName,
        phone: this.form.phone,
        id: this.editId,
        password: this.form.password,
        userId: this.userId,
        experiences: this.form.experiences,
        jobs: this.form.jobs,
        identity: this.form.identity
      }).then((response) => {
        console.log(response)
        this.$message({ message: '提交成功', type: 'success' })
        this.dialogVisible = false
        this.getList()
        this.imgFile = null
        this.form.avatar = null
        this.isPassword = false
        this.isPhone = false
      })
    },
    handleStatus(row, index) {
      console.log(row)

      this.$confirm(
        `是否确认${row.adminStatus === 1 ? '禁用' : '启用'}该员工？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        Employee.organizeEmployeeStatus({
          id: row['userId'],
          status: 1 - row.adminStatus
        }).then((response) => {
          this.$message({ message: '操作成功', type: 'success' })
          this.list[index]['adminStatus'] = 1 - row.adminStatus
        })
      })
    },
    handleDel(row, index) {
      console.log(row)

      this.$confirm('是否确认删除该员工？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Employee.organizeEmployeeDel({
          userId: row['userId']
        }).then((response) => {
          this.$message({ message: '操作成功', type: 'success' })
          this.list.splice(index, 1)
        })
      })
    },
    goToSearch() {
      this.getList()
    },
    defaultList() {
      if (this.listQuery.keyword === '') {
        this.listQuery.currentPage = 1
        this.getList()
      }
    },
    handleRemove(file, fileList) {
      console.log('handleChange')
      console.log(file)
      this.hideUpload = false
    },
    handleChange(file, fileList) {
      console.log('handleChange' + fileList.length)
      console.log(file)
      this.imgFile = fileList.length > 0 ? file : null
      this.hideUpload = fileList.length >= 1
    }
  }
}
</script>
<style lang="scss" scoped>
.el-form-item {
  margin-bottom: 10px;
}
.el-form-item__label {
  font-weight: 400;
}
.hide /deep/.el-upload--picture-card {
  display: none;
  width: 100px;
  height: 100px;
}
/deep/.el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 110px;
}
/deep/.el-upload-list--picture-card /deep/.el-upload-list__item {
  width: 100px;
  height: 100px;
}
/deep/ .el-form-item {
  margin-bottom: 18px;
}
.el-icon-check {
  margin-left: 10px;
  color: green;
}
.el-icon-close {
  margin-left: 10px;
  color: red;
}
/deep/ .el-input {
  width: 78%;
}
/deep/ .el-textarea {
  width: 78%;
}
/deep/ .el-select {
  width: 200px !important;
}
/deep/ .el-textarea__inner {
  height: 80px !important;
}
</style>
